package com.wjy.icu.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wjy.icu.common.annotation.PassToken;
import com.wjy.icu.common.core.domain.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * @Description: 登录拦截器
 * @author: wangjunyong
 * @date: 2019/4/24 11:29
 */
public class LoginAuthInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LoginAuthInterceptor.class);

    //    @Value("${com.nb.wjy.holdhealth.interceptor.debugger}")
    @Value("true")
    boolean debuggerMode;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 从 http 请求头中取出 token
//        logger.info("token校驗："+token);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //排除swagger

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        return true;
    }


    /**
     * 创建错误相应
     *
     * @param errorMsg
     * @param response
     * @throws Exception
     */
    private void createError(String errorMsg, String token, HttpServletResponse response) throws Exception {
        String errorJson = new ObjectMapper().writeValueAsString(R.error(HttpStatus.UNAUTHORIZED.value(), errorMsg));
        logger.error("错误：token校验错误。Token=>" + token + "。");
        this.createErrorResponseHeader(response);
        response.getWriter().print(errorJson);
    }

    /**
     * 创建错误响应头
     *
     * @param response
     */
    private void createErrorResponseHeader(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
    }
}
